<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Document</title>
</head>
<body>
	<script>
		// 自带promise：
		// new Promise(function(resolve,reject){
		// 	resolve("resolve方法被调用")；
		// 	// reject("reject方法被调用")
		// }).then(res=>{
		// 	console.log("成功状态的函数被调用了")
		// },err=>{
		// 	console.log("失败状态的函数被调用了")
		// })


		// 自己封装一个promise：
		class myPromise{
			// 定义状态
			static PENDING = "pending";
			static FULFILLED = "fulfilled";
			static REJECTED = "rejected";
			constructor(executor){
				this.status = myPromise.PENDING;
				this.value = null;
				try{
					executor(this.resolve.bind(this),this.reject.bind(this))
				}catch(err){
					console.log("执行者产生错误:",err)
					this.reject(err);				
				}
				
			};
			// 定义resolve方法
			resolve(value){
				if(this.status==myPromise.PENDING){
					this.status=myPromise.FULFILLED;
					this.value= value;
				}
			};
			// 定义reject方法
			reject(value){
				if(this.status==myPromise.PENDING){
					this.status=myPromise.REJECTED;
					this.value= value;
				}
			};
			// 定义then方法：
			then(onfulfilled,onRejected){
				// 判断用户是否传入函数参数、
				if (typeof onfulfilled != "function") {
					onfulfilled=()=>{
						onfulfilled(this.value);
					}
				}

				if (typeof onRejected != "function") {
					onRejected=()=>{
						onRejected(this.value);
					}
				}

				if (this.status==myPromise.FULFILLED) {
					onfulfilled(this.value);
				}

				if (this.status==myPromise.REJECTED) {
					onRejected(this.value);
				}
			}
		}






		// 使用自定义的promise
		var mypromise = new myPromise((resolve,reject)=>{
							// resolve("1111");
							reject("22222",	a)
						})

		console.log("测试自己封装的promise：", mypromise)


	</script>
</body>
</html>